﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VirtualPress.Infrastructure.Entities.Entity;
using VirtualPress.Infrastructure.Entities;
using System.Web;
using System.IO;
using VirtualPress.Infrastructure.Entities.Repository;
using VirtualPress.Infrastructure.Entities.Enum;
using System.Linq.Expressions;

namespace VirtualPress.Portal.Biz
{
    public class CommonBiz
    {
        #region PublishApply
        public static PublishApply NewPublishApply(PublishApply apply)
        {
            if (apply != null) 
            {
                apply = apply.PostAdd();
                return apply;
            }
            return null;
        }
        public static List<PublishApply> GetAllPublishApply(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.PublishApply
                            orderby c.Id descending
                            select c)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c=>new PublishApply().Set(c))
                           .ToList();
                return list;
            }
        }
        public static int GetPageOfPublishApply()
        {
            return new PublishApply().Count(c => true);
        }
        public static PublishApply EditPublishApply(PublishApply apply)
        {
            if (apply != null)
            {
                return apply.PostModify();
            }
            return null;
        }
        public static void DeletePublishApply(int id)
        {
            var user = new User().Find(HttpContext.Current.User.Identity.Name);
            if (user != null && user.SystemRole == Infrastructure.Entities.Enum.UserRole.Admin)
            {
                var apply = new PublishApply().Find(id.ToString());
                if (apply != null)
                {
                    apply.PostDelete();
                }
            }
        }

        public static List<Book> GetAllBook(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Book
                            orderby c.Id descending
                            select c)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new Book().Set(c))
                           .ToList();
                return data;
            }
        }
        public static Book NewBook(Book entity,string upload)
        {
            if (entity != null)
            {
                var file = HttpContext.Current.Request.Files[upload];
                string appendixPath = string.Empty;
                if (file != null && file.ContentLength > 0)
                {
                    var fileInfo = new FileInfo(file.FileName);
                    string extendName = fileInfo.Extension;
                    string fileName = fileInfo.Name.Replace(extendName, "");
                    string basedir = "/content/journal/" + entity.Name + "/coverimage/";
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                    }
                    file.SaveAs(HttpContext.Current.Server.MapPath(basedir + fileName + extendName));
                    appendixPath = basedir + fileName + extendName;
                }
                entity.CoverImg = appendixPath;
                //创建书籍
                entity = entity.PostAdd();
                return entity;
            }
            return null;
        }
        public static Book EditBookItem(Book model, string upload)
        {
            var oldbook = new Book().Find(model.Id.ToString());
            if (model != null && oldbook != null)
            {
                var file = HttpContext.Current.Request.Files[upload];
                string appendixPath = string.Empty;
                string appendixName = string.Empty;
                if (file != null && file.ContentLength > 0)
                {
                    try
                    {
                        System.IO.File.Delete(
                            HttpContext.Current.Server.MapPath(oldbook.CoverImg));
                    }
                    catch { }
                    var fileInfo = new FileInfo(file.FileName);
                    string extendName = fileInfo.Extension;
                    string fileName = fileInfo.Name.Replace(extendName, "");
                    string basedir = "/content/journal/" + model.Name + "/coverimage/";
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                    }
                    file.SaveAs(HttpContext.Current.Server.MapPath(basedir + fileName + extendName));
                    appendixPath = basedir + fileName + extendName;
                    oldbook.CoverImg = appendixPath;
                }
                oldbook.Name = model.Name;
                oldbook.Authors = model.Authors;
                oldbook.Translator = model.Translator;
                oldbook.Press = model.Press;
                oldbook.ISBN = model.ISBN;
                oldbook.FXFW = model.FXFW;
                oldbook.BC = model.BC;
                oldbook.YC = model.YC;
                oldbook.KB = model.KB;
                oldbook.Pages = model.Pages;
                oldbook.Characters = model.Characters;
                oldbook.CYZ = model.CYZ;
                oldbook.Price = model.Price;
                oldbook.Introduction = model.Introduction;
                oldbook.Buy = model.Buy;
                oldbook.PubDate = model.PubDate;
                oldbook.PrintDate = model.PrintDate;
                oldbook.Pack = model.Pack;
                oldbook.Content = model.Content;
                oldbook.AboutAuthor = model.AboutAuthor;
                oldbook.Comments = model.Comments;
                //创建书籍
                oldbook = oldbook.PostModify();
                return oldbook;
            }
            return null;
        }
        public static void DeleteBookItem(int id)
        {
            var user = new User().Find(HttpContext.Current.User.Identity.Name);
            if (user != null && user.SystemRole == Infrastructure.Entities.Enum.UserRole.Admin)
            {
                var book = new Book().Find(id.ToString());
                if (!String.IsNullOrEmpty(book.CoverImg))
                {
                    try
                    {
                        System.IO.File.Delete(
                            HttpContext.Current.Server.MapPath(book.CoverImg));
                    }
                    catch { }
                }
                if (book != null)
                {
                    book.PostDelete();
                }
            }
        }
        public static int GetPageOfBooks()
        {
            return new Book().Count(c=>true);
        }
        #endregion

        #region 新闻
        public static List<News> GetAllNews(NewsType newsType, int orgId, OrganizationType orgType, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.News
                    .Where(c => c.OrgId == orgId && c.OrgType == (int)orgType && c.Type == (int)newsType)
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new News()
                    {
                        Content = c.Content,
                        CreateDate = c.CreateDate,
                        DisplayEditor = c.DisplayEditor,
                        Editor = c.Editor,
                        Form = c.Form,
                        Id = c.Id,
                        Title = c.Title
                    }).ToList();
                return list;
            }
        }
        public static List<News> GetAllNews(Expression<Func<T_News, bool>> where, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.News
                    .Where(where)
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new News()
                    {
                        Content = c.Content,
                        CreateDate = c.CreateDate,
                        DisplayEditor = c.DisplayEditor,
                        Editor = c.Editor,
                        Form = c.Form,
                        Id = c.Id,
                        Title = c.Title
                    }).ToList();
                return list;
            }
        }
        public static int GetAllNewsForPage(int orgId, OrganizationType orgType, NewsType newsType)
        {
            using (Context ctx = new Context())
            {
                return ctx.News.Count(c => c.OrgId == orgId && c.OrgType == (int)orgType && c.Type == (int)newsType);
            }
        }
        public static int GetAllNewsForPage(Expression<Func<T_News, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.News.Count(where);
            }
        }
        public static bool DeleteNews(int id)
        {
            var news = new News().Find(id.ToString());
            if (news != null)
            {
                return news.PostDelete() != null;
            }
            return false;
        }
        public static News SaveNews(News news)
        {
            var item = news.PostAdd();
            return item;
        }
        #endregion

        #region 下载
        public static List<Download> GetAllDownloadFile(DownloadType downloadType,OrganizationType orgType,int orgId,
            int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.Download
                    .Where(c => c.OrgId == orgId && c.OrgType == (int)orgType && c.Type == (int)downloadType)
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new Download()
                    {
                        CreateDate = c.CreateDate,
                        Path = c.Path,
                        Remark = c.Remark,
                        Type = (DownloadType)c.Type,
                        Id = c.Id,
                        Title = c.Title
                    }).ToList();
                return list;
            }
        }
        public static List<Download> GetAllDownloadFile(Expression<Func<T_Download, bool>> where, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.Download
                    .Where(where)
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new Download()
                    {
                        Path = c.Path,
                        Remark = c.Remark,
                        Type = (DownloadType)c.Type,
                        CreateDate = c.CreateDate,
                        Id = c.Id,
                        Title = c.Title
                    }).ToList();
                return list;
            }
        }
        public static int GetAllDownloadFileForPage(DownloadType downloadType, OrganizationType orgType, int orgId)
        {
            using (Context ctx = new Context())
            {
                return ctx.Download.Count(c => c.OrgId == orgId && c.OrgType == (int)orgType && c.Type == (int)downloadType);
            }
        }
        public static int GetAllDownloadFileForPage(Expression<Func<T_Download, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.Download.Count(where);
            }
        }
        public static bool DeleteDownloadFile(int id)
        {
            var file = new Download().Find(id.ToString());
            if (file != null)
            {
                return file.PostDelete() != null;
            }
            return false;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="title"></param>
        /// <param name="remark"></param>
        /// <param name="downloadType"></param>
        /// <param name="OrgName">所属机构机构名称</param>
        /// <param name="fileControlName"></param>
        /// <returns></returns>
        public static Download SaveDownloadFile(int OrgId, OrganizationType orgType, string title,string remark, DownloadType downloadType, 
            string OrgName, string fileControlName)
        {
            var download = new Download()
            {
                OrgId = OrgId,
                Type = downloadType,
                Title = title,
                Remark = remark,
                CreateDate = DateTime.Now,
                OrgType = orgType
            };
            var file = System.Web.HttpContext.Current.Request.Files[fileControlName];
            if (file != null && file.ContentLength > 0)
            {
                string basedir = String.Format("/content/{0}/{1}/downloadFiles/",
                    downloadType == DownloadType.JournalFile ? "journal" :
                    downloadType == DownloadType.MeetingFile ? "meeting" : "System",
                    OrgName);
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                var fileinfo = new FileInfo(file.FileName);
                string filePath = basedir + title + fileinfo.Extension;
                file.SaveAs(HttpContext.Current.Server.MapPath(filePath));
                download.Path = filePath;
            } 
            var item = download.PostAdd();
            return item;
        }
        public static void EditDownloadFile(int id, string title, string remark, string orgName, string fileControlName)
        {
            var download = new Download().Find(id.ToString());
            if (download != null)
            {
                download.Title = title;
                download.Remark = remark;
                var file = System.Web.HttpContext.Current.Request.Files[fileControlName];
                if (file != null && file.ContentLength > 0)
                {
                    string basedir = String.Format("/content/{0}/{1}/downloadFiles/",
                        download.Type == DownloadType.JournalFile ? "journal" :
                        download.Type == DownloadType.MeetingFile ? "meeting" : "System",
                        orgName);
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                    }
                    var fileinfo = new FileInfo(file.FileName);
                    string filePath = basedir + title + fileinfo.Extension;
                    file.SaveAs(HttpContext.Current.Server.MapPath(filePath));
                    download.Path = filePath;
                }
            }
            download.PostModify();
        }
        #endregion

        public static List<ImportantPan> GetPan(OrganizationType orgType, int id, int page, int pageSize)
        {
            return new ImportantPan().FindAll(c => c.meetingId == id)
                .OrderByDescending(c => c.Id)
                .Skip(page * pageSize)
                .Take(pageSize)
                .ToList();
        }

        public static ImportantPan NewImportantPan(ImportantPan importantPan)
        {
            if (importantPan != null)
            {
                importantPan.PostAdd();
                return importantPan;
            }
            return null;
        }
    }   
}
